package com.itsu.spbspider.component.interceptors;

import com.itsu.spbspider.entity.User;
import com.itsu.spbspider.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
//        System.out.println(requestURI);
        User user = (User) request.getSession().getAttribute("user");
        if (StringUtils.isNotBlank(requestURI) && (requestURI.endsWith(".png") || requestURI.endsWith(".jpg") || requestURI.endsWith(".gif") || requestURI.endsWith(".js")
                || requestURI.endsWith(".css") || requestURI.endsWith(".ttf")) || requestURI.endsWith(".woff2") || requestURI.equals(".txt"))
            return true;

        if (user == null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("user")) {
                        String[] split = cookie.getValue().split("-=-");
                        if (split.length == 2) {
                            User u = new User();
                            u.setUsername(split[0]);
                            u.setPassword(split[1]);
                            u = userService.loginWithCookie(u);
                            if (u != null) {
                                request.getSession().setAttribute("user", u);
                                return true;
                            }
                        }
                        break;
                    }
                }
            }
            log.warn("用户未登录,将跳转到登录页");
            response.sendRedirect("/login");
            return false;
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
}
